package priv.pic.to.link.main.util;

import javax.swing.*;
import java.awt.*;

/**
 * Created on 2018/4/26.
 */
public class TipUtil {

    public static void tip(String tip) {
        new TipWindow().launchFrame(tip, null);
    }

    public static void warn(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

    public static boolean confirm(String message) {
        int i = JOptionPane.showConfirmDialog(null, message);
        return i == 0;
    }

    private static class TipWindow extends JWindow {
        public void launchFrame(String tip, Color color) {
            int default_width = 500;
            int default_columns = 23;
            int columns = Math.min(tip.length(), default_columns);
            color = color == null ? Color.BLUE : color;
            Font font = new Font(null, Font.ITALIC, 20);
            int width = Math.min(10 + font.getSize() * columns, default_width);
            int row = (tip.length() - 1) / default_columns + 1;
            int height = (font.getSize() + 5) * row;


            this.setVisible(true);
            this.setOpacity(1f);
            this.setSize(width, height);
            this.setAlwaysOnTop(true);
            this.setBackground(Color.black);

            this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - width, 0);

            JTextArea textArea = createTextArea(tip, font, color, columns);
            textArea.setBounds(0, 0, width, height);

            this.getLayeredPane().add(textArea);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            this.dispose();
        }

        private JTextArea createTextArea(String tip, Font font, Color color, int columns) {
            JTextArea textArea = new JTextArea();
            textArea.setForeground(color);
            textArea.setFont(font);
            textArea.setVisible(true);


            if (tip.contains("\n")) {
                textArea.append(tip);
            } else {
                int index = 0;
                while (true) {
                    textArea.append(tip.substring(index, Math.min(index + columns, tip.length())));
                    index += columns;
                    if (index >= tip.length()) {
                        break;
                    }
                    textArea.append("\t\n");
                }
            }
            return textArea;
        }
    }
}